import { stringify } from 'qs';

const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};

const getDate = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${formatNumber(
    date.getMonth() + 1,
  )}-${formatNumber(date.getDate())}`;
};

/**
 * @name: 根据时间戳返回数组版年月日时间
 * @description:
 * @msg:
 * @param {type}
 * @return {type}
 */
const getYMDS = (timestamp) => {
  const date = new Date(timestamp);
  return [
    date.getFullYear(),
    formatNumber(date.getMonth() + 1),
    formatNumber(date.getDate()),
    formatNumber(date.getHours()),
    formatNumber(date.getSeconds()),
  ];
};

const getRandom = () => {
  const chars = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'g',
    'h',
    'i',
    'j',
    'k',
    'l',
    'm',
    'n',
    'o',
    'p',
    'q',
    'r',
    's',
    't',
    'u',
    'v',
    'w',
    'x',
    'y',
    'z',
  ];
  let nums = '';
  for (var i = 0; i < 32; i++) {
    var id = parseInt(Math.random() * chars.length);
    nums += chars[id];
  }
  return nums;
};

const report = (content) => {
  const host = 'cn-shenzhen.log.aliyuncs.com';
  const project = '';
  const logstore = '';

  const REPORT_URL = `http://${project}.${host}/logstores/${logstore}/track_ua.gif?APIVersion=0.6.0&`;
  content = {
    ...content,
    traceId: 'xxx',
  };
  const url = REPORT_URL + stringify(content);

  let img = new Image();
  img.onload = img.onerror = function () {
    img = null;
  };
  img.src = url;
};

export { getDate, getYMDS, getRandom, report };
